const config = require('config')
const nextcloud = config.get('nextcloud')
const request = require('request-promise')
const share_provision_path = '/ocs/v2.php/apps/files_sharing/api/v1/shares'
import {ncOptions,getBase64Auth} from '../common'
const lnkgGroup = config.get('nextcloud.group')


const getShares = async(user)=>{
    let options = {...ncOptions}, result
    options.method = 'GET'
    options.headers.Authorization = getBase64Auth(user.id, user.passwd)
    options.uri = `${nextcloud.host}${share_provision_path}`
    result = await request(options)
    result = result&&result.ocs&&result.ocs.data
    return result
}

export const addShareLink = async (user, path, groupShare) => {
    let options = {...ncOptions},result
    options.headers.Authorization = getBase64Auth(user.id, user.passwd)
    options.uri = `${nextcloud.host}${share_provision_path}`
    options.form = {path,shareType:3}
    if(groupShare){
        options.form = {path, shareType:1, shareWith:lnkgGroup, permissions:31}
    }
    result = await request(options)
    result = result.ocs && result.ocs.data
    return result
}

export const getShareByPath = async (user,filePath)=>{
    let result = await getShares(user)
    if(result&&result.length){
        for(let share of result){
            if(share.path==filePath&&share.token){
                return share
            }
        }
    }
}

export const getShareByFileType = async (user,patterns)=>{
    let result = await getShares(user)
    if(result&&result.length){
        return result.filter((share)=>{
            return patterns.length?patterns.some(pattern=>share.path.endsWith(pattern)):share
        })
    }
}

export const getShareById = async (user,id)=>{
    let result = await getShares(user)
    if(result&&result.length){
        for(let share of result){
            if(share.token == id){
                return share
            }
        }
    }
}

export const delShare = async (user,id) => {
    let options = {...ncOptions},result
    options.headers.Authorization = getBase64Auth(user.id, user.passwd)
    options.uri = `${nextcloud.host}${share_provision_path}/${id}`
    options.method = 'DELETE'
    result = await request(options)
    result = result.ocs && result.ocs.data
    return result
}
